<?php
namespace plugins\pay\model;
use think\Model;
use think\Db;
use plugins\pay\model\AlipayModel;
use plugins\pay\model\WeChatPayModel;

/**
 * 支付业务的基类
 */
class BaseModel extends Model{
    /**
     * 处理实际业务的属性和方法
     */
    protected $tradeType="base";//交易类型
    //创建订单，等待用户结账
    public function createAsyncOrder($uid,$params){
        return [
            "title"=>"测试",
            "money"=>1,
            "description"=>"测试交易",
            "trade_data"=>[]
        ];
    }
    //用户已经结账，结算订单
    public function commitAsyncOrder($tradeData){
        //$tradeData参数是generateOrder的返回的数组中的trade_data字段
        $this->record["message"]="交易成功";
        return true;
    }
    //iOS内购，用户直接结账
    //$params是iOS内购的参数，例如
    // {
    //     "quantity": "1",
    //     "product_id": "z_8",
    //     "transaction_id": "1000000366413210",
    //     "original_transaction_id": "1000000366413210",
    //     "purchase_date": "2018-01-15 07:31:32 Etc/GMT",
    //     "purchase_date_ms": "1516001492000",
    //     "purchase_date_pst": "2018-01-14 23:31:32 America/Los_Angeles",
    //     "original_purchase_date": "2018-01-15 07:31:32 Etc/GMT",
    //     "original_purchase_date_ms": "1516001492000",
    //     "original_purchase_date_pst": "2018-01-14 23:31:32 America/Los_Angeles",
    //     "is_trial_period": "false"
    // }
    public function tradeWithApple($uid,$params){
        return [
            "title"=>"测试",
            "money"=>1,
            "description"=>"测试交易"
        ];
    }

    public function generateTradeNo($uid,$tradeType){
        // return $uid."_".time();
        return $uid."_".$tradeType."_".time();
    }
    /**
     * 连贯操作-创建异步支付:获取模型类->创建交易->(保存记录并且)调用支付SDK->(在相应的支付方式类中)调用相应的支付方式
     */
    public $record;
    static function getModel($name){
        if($name==="topup"){
            return new plugins\pay\model\TopupModel;
        }
        else{
            return new self;
        }
    }
    public function createAsyncTrade($uid,$params){
        $tradeNo=$this->generateTradeNo($uid,$this->tradeType);
        $order=$this->createAsyncOrder($uid,$params);
        $data=[
            "trade_no"=>$tradeNo,
            "trade_type"=>$this->tradeType,
            "title"=>$order["title"],
            "money"=>$order["money"],
            "description"=>$order["description"],
            "trade_data"=>json_encode($order["trade_data"]),
            "time"=>date("Y-m-d H:i:s"),
            "status"=>0
        ];
        $this->record=$data;
        return $this;
    }
    public function alipay(){
        $this->record["out_type"]="alipay";
        $id=Db::name('pay_trade')->insertGetId($this->record);
        if(!$id){
            $this->error="创建订单失败";
            return false;
        }
        $data["id"]=$id;
        $pay=new AlipayModel();
        $pay->tradeModel=$this;
        return $pay;
    }
    public function wechat(){
        $this->record["out_type"]="wechat";
        $id=Db::name('pay_trade')->insertGetId($this->record);
        if(!$id){
            $this->error="创建订单失败";
            return false;
        }
        $data["id"]=$id;
        $pay=new WeChatPayModel();
        $pay->tradeModel=$this;
        return $pay;
    }
    //更新交易状态
    static function updateAsyncTrade($tradeNo,$outTradeNo=""){
        $data=Db::name('pay_trade')->where(["trade_no"=>$tradeNo])->find();
        if(!$data){
            return false;
        }
        $model=self::getModel($data["trade_type"]);
        
        if($outTradeNo){
            $data["out_trade_no"]=$outTradeNo;
        }
        if($record["status"]==="1"){
            return true;
        }
        $tradeData=json_decode($record["trade_data"],true);
        $result=$model->commitAsyncOrder($tradeData);
        if(!$result){
            return false;
        }
        $record["status"]=1;
        return Db::name('pay_trade')->update($record);
    }
    //创建已经支付的交易(比如iOS内购)
    public function createSyncTrade($uid,$outTradeNo,$params){
        $record=Db::name('pay_trade');
        $data=$record->where(["out_trade_no"=>$outTradeNo])->find();
        if($data&&$data["status"]==="1"){
            $this->error="交易已经被结算，请勿重复提交";
            return false;
        }

        $order=$this->tradeWithApple($uid,$params);
        if(!$order){
            return false;
        }
        $data=[
            "trade_no"=>$this->generateTradeNo($uid,$this->tradeType),
            "trade_type"=>$this->tradeType,
            "out_trade_no"=>$outTradeNo,
            "title"=>$order["title"],
            "money"=>$order["money"],
            "description"=>$order["description"],
            "time"=>date("Y-m-d H:i:s"),
            "status"=>1,
            "message"=>"交易成功"
        ];
        
        $id=$record->insertGetId($data);
        if(!$id){
            return false;
        }
        $data["id"]=$id;
        return $data;
    }
}